package com.tanhua.server.interceptor;

import com.tanhua.domain.db.User;
import com.tanhua.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统一token处理类
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    /**
     * 进入controller之前
     * 进入token处理：拦截token 解析token 获取用户信息 存入ThreadLocal
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("*********************拦截器被执行了。。。");
        //1.通用request对象获取请求头中Authorization（token）
        String token = request.getHeader("Authorization");
        log.debug("*********************Authorization：：："+token);
        //2.请求头中Authorization（token） 非空判断 如果为空401 用户没有访问权限 return false;
        if(StringUtils.isEmpty(token)){
            response.setStatus(401);
            return false;
        }
        //3.如果没有获取user信息，返回401
        User user = userService.getUserByToken(token);
        log.debug("*********************user：：：："+user.toString());
        if(user == null){
            response.setStatus(401);
            return false;
        }
        //4.根据token获取user信息 ,存入ThreadLocal对象
        UserHolder.setUser(user);
        return true;
    }
}
